// -------------------每日精彩--------------------------------------
var app = getApp();
var config = require('../../../config.js');
var index = 0;
var timer; // 计时器
var currQuestion;
//圆形进度条 
var interval;
var varName;
var ctx = wx.createCanvasContext('canvasArcCir');
Page({

  /**
   * 页面的初始数据
   * 我的理解是 页面渲染的数据必须在data中设置
   * 如果是当前js自己需要的一些变量数据可以在顶部全局进行设置（当然写在data中可能更好吧 zhc ）
   */
  data: {
    questionList: [],
    time: 0,  //当前时长
    totalTime: 20,//总时长
    currentQuestionPos: 1,
    //服务器需要的数据集合
    answersData:[],
    rightCount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    index = 0;
    this.getQuestionList();
    this.setData({
      userFaceUrl: app.globalData.userInfo.avatarUrl,
      nickName: app.globalData.userInfo.nickName
    });

  },
  /**
   * 每次打开页面都会调用一次。
   */
  onShow: function(){


  },
  /**
   * 一个页面只会调用一次，代表页面已经准备妥当，可以和视图层进行交互。
   */
  onReady: function(){
    this.drawDefaultArc();
  },

  //获取10条问题
  getQuestionList: function () {
    var that = this;
    console.log(config.answerQuestion);
    wx.request({
      url: config.answerQuestion,
      method:'POST',
      data: {
        //题库分类  1每日精彩
        type: 1
      },
      success: function (res) {
        if (res.data.success == 0){
          that.setData({
            questionList: res.data.rows
          });
          that.getNextQuestion();
          //保存数据 下次进来接着答题
          wx.setStorageSync(config.questionList, res.data.rows);
          //延迟1s给用户反应
          setTimeout(function () {
            //开启动画和定时器
           
            that.startProgressAnim();
            that.startTimer();

          },1000);

        }
      },

      fail: function (error) {
        console.log(error)
      }
    })
  },
  //获取下一个问题
  getNextQuestion: function () {
    currQuestion = this.data.questionList[index];
    var questionDesc = currQuestion.content;
    var answerList = currQuestion.answers;
    this.setData({
      currQuestion: currQuestion,
      questionDesc: questionDesc,
      answerList: answerList,
      isShowAnswer: false,
      currentQuestionPos: index
    })
    
  
  },

  //选择答案点击事件
  selectedCase: function (event) {
    var that = this;
    if (that.data.isShowAnswer) {
      //如果已经显示答案，不能再次选择答案
      return;
    }
    //获取选择id
    var answerid = event.currentTarget.dataset.answerid;
    var correct = event.currentTarget.dataset.correct;
    console.log(answerid)
    that.setData({
      isShowAnswer: true,
      answerid: answerid,
      isAnswerRight: correct==1
    });
    //保存数据 等10道题全部结束 统一提交
    var answerObj={} ;
    answerObj.qid = that.data.currQuestion.id;
    answerObj.aid = answerid;
    answerObj.right = correct==1?0:1;
    that.data.answersData.push(answerObj);
  //设置缓存 并且向服务器提交答案
    that.setDataAndPost(correct);

    that.pauseTimer();
    clearInterval(varName);
    if (index != that.data.questionList.length) {
      // 开始下一题
      that.startNextQuestion();
    }

  }, 


//设置缓存 并且向服务器提交答案
  setDataAndPost: function (correct){
  var that = this;
  if (index == this.data.questionList.length - 1) {
    console.log("用户答到最后一题 提交数据");
    setTimeout(function () {
      //用户答到最后一题 提交数据
      that.postAnserDataToServer();
      wx.setStorageSync(config.isFinished, 1);
    },500);
   
  } else {
    //保存数据 下次进来接着答题
    wx.setStorageSync(config.currentPostion, this.data.currentQuestionPos);
    wx.setStorageSync(config.isFinished, 0);
   
  }
  index++;

  //计算用户答对了几道题
  var count = that.data.rightCount + 1;
  if (correct == 1) {
    that.setData({
      rightCount: count
    });
    app.globalData.bgMusicR.play()
  }else{
    app.globalData.bgMusicW.play()
  }
 
},




  //开始下一题的答题
  startNextQuestion: function(){
    var that = this;
    //自动跳转到下一题
    setTimeout(function () {
      console.log("下一题开始了！！！！！");
      that.getNextQuestion();
      that.startTimer();
      that.startProgressAnim();
    }, 2000);

  },

  //时间到自动显示答案 用户没有点击行为 
  autoShowCase: function(){
    app.globalData.bgMusicW.play()
    if (this.data.isShowAnswer){
      //如果已经显示答案，不能再次选择答案
        return;
    }
    this.setData({
      isShowAnswer: true,
      answerid: -1,
      isAnswerRight: false

    })
    //设置缓存 并且向服务器提交答案
    //保存数据 等10道题全部结束 统一提交
    var answerObj = {};
    answerObj.qid = this.data.currQuestion.id;
    answerObj.right = 1;
    this.data.answersData.push(answerObj);
    this.setDataAndPost(-1);
    if (index < this.data.questionList.length ) {
      // 开始下一题
      this.startNextQuestion();
    }
   

    

  },

  // 开始倒计时
  startTimer: function () {
    this.setData({
      time: 0
    });
    this.countDownd();

  },

  // 自定义的暂停按钮  
  pauseTimer: function () {
    console.log("定时任务停止");
    if(timer){
      clearTimeout(timer);
    }
   
  },

  // 倒计时
 countDownd: function () {
   var that = this;
    timer = setTimeout(function () {
      var currTime = that.data.time + 1;
      console.log("----Countdown----"+ currTime);
      that.setData({
        time: currTime
      });

      if (currTime == that.data.totalTime){
        //当时间到达20秒 结束计时
        that.pauseTimer();
        if (!that.data.isShowAnswer){
          //自动显示答案
          that.autoShowCase();

        }else{
          console.log("currentIndex==="+index)
          // if (index != that.data.questionList.length) {
          //   // 开始下一题
          //   that.startNextQuestion();
          // }
        
        }
      }else{
        that.countDownd();
      }
    }, 1000);
  },

  /**
   * 向服务器提交本轮答案
   */
  postAnserDataToServer: function(){
    var that = this;
    wx.request({
      url: config.postAnswer,
      method: "POST",
      data:{
        openid: app.globalData.openid,
        //题库分类  1每日精彩
        type: 1,
        answers: that.data.answersData
      },
      success: function (res) {
        if (res.data.success == 0) {
          // 跳转到个人成就页面
          wx.redirectTo({
            url: '../../toplistshow/toplistshow?levelName=' + res.data.rows.levelName + '&title=' + res.data.rows.title
          })
        }
      },

      fail: function (error) {
        console.log(error)
      }

    })


  },


  /**
   * 画默认的圆形
   */
  drawDefaultArc: function(){
    //创建并返回绘图上下文context对象。
    var cxt_arc = wx.createCanvasContext('canvasCircle');
    cxt_arc.setLineWidth(3);
    cxt_arc.setStrokeStyle('#e2e2e2');
    cxt_arc.setLineCap('round');
    cxt_arc.beginPath();

    cxt_arc.arc(40, 40, 26, 0, 2 * Math.PI, false);

    cxt_arc.stroke();
    cxt_arc.draw();
  },

  drawArc: function (s, e) {
    var x = 40, y = 40, radius = 26;
    ctx.setLineWidth(3);
    ctx.setStrokeStyle('#ff6600');

    ctx.setLineCap('round');
    ctx.beginPath();
    ctx.arc(x, y, radius, s, e, false);
    ctx.stroke()
    ctx.draw()
  },
  
  /**
   *开启度条
   */
  startProgressAnim: function(){
    clearInterval(varName);
    var that = this;
    var step = 1, startAngle = 0.5 * Math.PI, endAngle = 0;
    var animation_interval = 200, n = that.data.totalTime * 1000 / 200;
    var animation = function () {
      if (step <= n) {
        endAngle = step * 2 * Math.PI / n + 0.5 * Math.PI;
        that.drawArc(startAngle, endAngle);
        step++;
      } else {
        clearInterval(varName);
      }
    };
    varName = setInterval(animation, animation_interval);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //当页面卸载时 停止定时任务
    this.pauseTimer();
  },



})